package com.slipper.system.employee;

import java.util.*;
import java.util.stream.Collectors;

import com.slipper.common.bo.Result;
import com.slipper.common.tree.Node;
import com.slipper.system.api.menu.bo.MenuBO;
import com.slipper.system.api.role.bo.RoleBO;
import com.slipper.system.api.role.service.IRoleSv;
import javax.annotation.Resource;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.slipper.system.api.employee.bo.EmployeeBO;
import com.slipper.system.api.employee.service.IEmployeeSv;
import com.slipper.system.api.organization.bo.OrganizationBO;
import com.slipper.system.api.organization.service.IOrganizationSv;
import com.slipper.system.common.Constants;
import com.slipper.common.permit.PermitAll;
import com.slipper.common.tree.TreeInfo;
import com.slipper.common.tree.TreeUtil;
import com.slipper.common.util.ResultUtil;

/**
 * 员工信息表
 *
 * @date 2020-03-26 14:59:54
 */
@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Resource
    private IEmployeeSv employeeSv;
    @Resource
    private IOrganizationSv organizationSv;
    @Resource
    private IRoleSv roleSv;

    @PermitAll
    @PostMapping("/queryBy")
    public String queryBy(@RequestBody EmployeeBO bo) {
        return ResultUtil.toJson(employeeSv.queryBy(bo));
    }

    @PermitAll
    @PostMapping("/queryByIds")
    public String queryByIds(@RequestBody EmployeeBO bo) {
        Result<List<EmployeeBO>> result = employeeSv.queryByIds(bo);
        StringBuilder names = new StringBuilder();
        for (String id : bo.getIds()) {
            String name = "";
            for (EmployeeBO employeeBO : result.getData()) {
                if (id.equals(employeeBO.getId())) {
                    name = employeeBO.getName();
                    break;
                }
            }
            if (names.length() == 0) {
                names.append(name);
            } else {
                names.append(",").append(name);
            }
        }
        return ResultUtil.toJson(names.toString());
    }

    @PermitAll
    @PostMapping(value = "/queryList")
    public String queryList(@RequestBody EmployeeBO bo) {
        return ResultUtil.toJson(employeeSv.queryList(bo));
    }


    @PermitAll
    @PostMapping("/queryPage")
    public String queryPage(@RequestBody EmployeeBO bo) {
        return ResultUtil.toJson(employeeSv.queryPage(bo));
    }

    @PermitAll
    @PostMapping("/queryTree")
    public String queryTree() {
        OrganizationBO organizationQO = new OrganizationBO();
        organizationQO.setLevelName(Constants.NO);
        Result<List<OrganizationBO>> organizationResult = organizationSv.queryList(organizationQO);
        organizationResult.getData().forEach(organization -> {
            if (organization.getId().equals(organization.getParentId())) {
                organization.setParentId(null);
            }
        });

        EmployeeBO employeeQO = new EmployeeBO();
        employeeQO.setStatus(EmployeeBO.STATUS_ON);
        employeeQO.setValid(Constants.VALID);
        employeeQO.setSortField("e.ordinal asc, e.name asc");
        Result<List<EmployeeBO>> employeeResult = this.employeeSv.queryListWithOrg(employeeQO);
        int listSize = employeeResult.getData().size();
        for (int i = 0; i < listSize; i++) {
            employeeResult.getData().get(i).setOrdinal(i);
        }

        TreeInfo treeInfo = new TreeInfo("部门树");
        treeInfo.setRootId(Constants.ROOT_ID);
        treeInfo.setCanOp(false);
        treeInfo.setIdField("id");
        treeInfo.setPidField("parentId");
        treeInfo.setTextField("shortName");

        TreeInfo opTreeInfo = new TreeInfo("人员树");
        opTreeInfo.setConcatIdWithPid(true);
        opTreeInfo.setIdField("id");
        opTreeInfo.setPidField("organizationId");
        opTreeInfo.setTextField("name");

        Node rootNode = TreeUtil.buildTree(
                treeInfo,
                organizationResult.getData(),
                opTreeInfo,
                employeeResult.getData(),
                "asc");
        rootNode.setDisable(true);
        return ResultUtil.toJson(rootNode);
    }

    @PostMapping("/save")
    public String save(@RequestBody EmployeeBO bo) {
        return ResultUtil.toJson(employeeSv.save(bo));
    }

    @PostMapping("/delete")
    public String delete(@RequestBody EmployeeBO bo) {
        return ResultUtil.toJson(employeeSv.delete(bo));
    }

    @PostMapping("/queryUserRole")
    public String queryMenuOperator(@RequestBody MenuBO bo) {
        RoleBO roleBO = new RoleBO();
        roleBO.setEmployeeId(bo.getId());
        Result<List<RoleBO>> selectedRolesResult = this.roleSv.queryList(roleBO);

        roleBO = new RoleBO();
        roleBO.setCreateId(Constants.getCurrentUser().getEmployeeId());
        Result<List<RoleBO>> allRoleResult = this.roleSv.queryList(roleBO);
        allRoleResult.getData().sort(Comparator.comparing(RoleBO::getPower));

        Map<String, Object> result = new HashMap<>();
        result.put("selectedIds", selectedRolesResult.getData()
                .stream()
                .map(RoleBO::getId)
                .collect(Collectors.toList()));
        result.put("allRoles", allRoleResult.getData());
        return ResultUtil.toJson(result);
    }

    @PostMapping("/saveUserRole")
    public String saveUserRole(@RequestBody EmployeeBO bo) {
        return ResultUtil.toJson(employeeSv.saveUserRole(bo));
    }

    @PermitAll
    @PostMapping("/updatePassword")
    public String updatePassword(@RequestBody EmployeeBO bo) {
        bo.setId(Constants.getCurrentUser().getEmployeeId());
        if (employeeSv.updatePassword(bo).isSuccess()) {
            return ResultUtil.toSuccessJson("密码修改成功！");
        } else {
            return ResultUtil.toErrorJson("密码修改失败！");
        }
    }
}
